package org.hujunfeng.http;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 关闭监听器
 */
public class CloseListener implements Runnable{

    private ServerSocket serverSocket;

    private int shutdownPort;

    private AtomicBoolean closeBoolean;

    public CloseListener(ServerSocket serverSocket, Config config, AtomicBoolean atomicBoolean) {
        this.serverSocket = serverSocket;
        this.shutdownPort = config.getShutdownPort();
        this.closeBoolean = atomicBoolean;
    }

    @Override
    public void run() {
        try {
            // 1、建立UDP客户端
            DatagramSocket client = new DatagramSocket(shutdownPort);

            // 定义字节数组缓冲
            byte[] data = new byte[1];

            // 2、创建UDP数据包
            DatagramPacket packet = new DatagramPacket(data, 0, data.length);

            // 3、循环不断的监听
            while (true){
                try {
                    client.receive(packet);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 4、如果数据包的内容是0x01，证明是关闭，退出循环。
                if (data[0] == 0x01){
                    break;
                }
            }

            System.out.println("server is received close signal.");

            // 5、设置关闭为真。
            closeBoolean.set(true);

            // 6、关闭服务套接字
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
